package com.leadingsoft.pwxk.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.leadingsoft.pwxk.dto.BaseInfoDto;
import com.leadingsoft.pwxk.model.QBaseInfo;
import com.leadingsoft.pwxk.model.QPwBaseInfo;
import com.leadingsoft.pwxk.service.BaseInfoService;
import com.querydsl.core.Tuple;
import com.querydsl.jpa.impl.JPAQuery;

/**
 * 
 * @author ysh
 *
 */

@Service
public class BaseInfoServiceImpl implements BaseInfoService {

	private QBaseInfo qBaseInfo = QBaseInfo.baseInfo;

	private QPwBaseInfo qPwBaseInfo = QPwBaseInfo.pwBaseInfo;

	@Autowired
	private EntityManager em;

	@Override
	public BaseInfoDto getByDataId(String dataId) {
		BaseInfoDto baseInfoDto = new BaseInfoDto();
		JPAQuery<Tuple> query = new JPAQuery<>(em);
		query.select(qBaseInfo.entername, qBaseInfo.name_country, qBaseInfo.name_region, qBaseInfo.name_regiondetail,
				qBaseInfo.tradesname, qBaseInfo.productaddress);
		query.from(qBaseInfo).leftJoin(qPwBaseInfo).on(qBaseInfo.enterid.eq(qPwBaseInfo.enterid));
		query.where(qPwBaseInfo.dataid.eq(dataId));
		List<Tuple> fetch = query.fetch();
		fetch.forEach(t -> {
			baseInfoDto.setEntername(t.get(qBaseInfo.entername));
			baseInfoDto.setName_country(t.get(qBaseInfo.name_country));
			baseInfoDto.setName_region(t.get(qBaseInfo.name_region));
			baseInfoDto.setName_regiondetail(t.get(qBaseInfo.name_regiondetail));
			baseInfoDto.setTradesname(t.get(qBaseInfo.tradesname));
			baseInfoDto.setProductaddress(t.get(qBaseInfo.productaddress));
		});
		return baseInfoDto;
	}

//	@Cacheable(cacheNames = "codeTrade", sync = true, key = "'all'")
	@Override
	public Map<String, String> getTrade() {
		HashMap<String, String> map = new HashMap<String, String>();
		JPAQuery<Tuple> query = new JPAQuery<>(em);
		query.select(qBaseInfo.code_trade, qBaseInfo.tradesname);
		query.from(qBaseInfo);
		List<Tuple> result = query.fetch();
		for (Tuple row : result) {
			String code = row.get(qBaseInfo.code_trade);
			String name = row.get(qBaseInfo.tradesname);
			if (StringUtils.isNotBlank(code) && StringUtils.isNotBlank(name)) {
				map.put(code, name);
			}
		}
		return map;
	}

//	@Cacheable(cacheNames = "codeWsystem", sync = true, key = "'all'")
	@Override
	public Map<String, String> getWsystem() {
		HashMap<String, String> map = new HashMap<String, String>();
		JPAQuery<Tuple> query = new JPAQuery<>(em);
		query.select(qBaseInfo.cod_wsystem, qBaseInfo.wsystemname);
		query.from(qBaseInfo);
		List<Tuple> result = query.fetch();
		for (Tuple row : result) {
			String code = row.get(qBaseInfo.cod_wsystem);
			String name = row.get(qBaseInfo.wsystemname);
			if (StringUtils.isNotBlank(code) && StringUtils.isNotBlank(name)) {
				map.put(code, name);
			}
		}
		return map;
	}

}
